package app.gt.screen.mapwithroute;



import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;



import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import app.gt.R;
import app.gt.service.mapwithroute.RoadProvider;

public class MapScreen extends MapActivity {
  
static Context context; 
  


private app.gt.service.mapwithroute.Road mRoad;  
  MapController mapController;
  MapOverlay mapOverlay;
  MyLocationOverlay whereAmI;
  MapView myMapView;
 public Context uuuu;
  @Override
  protected boolean isLocationDisplayed() {
      return whereAmI.isMyLocationEnabled();
  }
  @Override
  protected boolean isRouteDisplayed() {
	    return false;
	  }


  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.defineroutemapscreen);
    
    
    myMapView = (MapView)findViewById(R.id.mapview);
    mapController = myMapView.getController();
    mapController.setZoom(17);
   
    myMapView.setSatellite(false);
    myMapView.setStreetView(true);
    myMapView.displayZoomControls(true);
    myMapView.setTraffic(true);
    
    whereAmI = new MyCustomLocationOverlay(this, myMapView);
    
    
 uuuu = getBaseContext();
   // Add the MyPositionOverlay
   //positionOverlay = new MyPositionOverlay();
   // List<Overlay> overlays = myMapView.getOverlays();
   //overlays.add(positionOverlay);
   
    LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);

    updateWithNewLocation(location);

    locationManager.requestLocationUpdates(provider, 2000, 10,   
                                           locationListener);
    
    new Thread() {
		@Override
		public void run() {
			double fromLat = 59.12861562162634, fromLon = 11.351918578147888, toLat = 59.91144356879879, toLon = 10.734179019927979;
			String url = RoadProvider
					.getUrl(fromLat, fromLon, toLat, toLon);
			InputStream is = getConnection(url);
			mRoad = RoadProvider.getRoute(is);
			mHandler.sendEmptyMessage(0);
		}
	}.start();
    
       
  }
  Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			//TextView textView = (TextView) findViewById(R.id.description);
			//textView.setText(mRoad.mName + " " + mRoad.mDescription);
			
			
			MapOverlay mapOverlay = new MapOverlay(mRoad,myMapView);
			List<Overlay> listOfOverlays = myMapView.getOverlays();
			listOfOverlays.clear();
			listOfOverlays.add(mapOverlay);
			listOfOverlays.add(whereAmI);
			myMapView.postInvalidate();
		
		};
	};
  private InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
  
  private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }
	 
    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status, 
                                Bundle extras){ }
  };

  private void updateWithNewLocation(Location location) {
   
    TextView myLocationText;
    myLocationText = (TextView)findViewById(R.id.description);
    String addressString = "No address found";

	if (location != null) {
       
      
      double latitude = location.getLatitude();
      double longitude = location.getLongitude();
      
      
      

      Geocoder gc = new Geocoder(this, Locale.getDefault());
      try {
        List<Address> addresses = gc.getFromLocation(latitude, 
                                                     longitude, 1);
        StringBuilder sb = new StringBuilder();
        if (addresses.size() > 0) {
          Address address = addresses.get(0);

          for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
            sb.append(address.getAddressLine(i)).append("\n");

            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
        }
        addressString = sb.toString();
      } catch (IOException e) {}
    } else {
     
    }
    myLocationText.setText("Your Current Position is:\n" + addressString);
  }
  @Override
  protected void onResume() {
  	super.onResume();
    whereAmI.enableMyLocation();
	whereAmI.runOnFirstFix(new Runnable() {
        public void run() {
            mapController.setCenter(whereAmI.getMyLocation());
        }
    });
}

  @Override
  public void onPause()
  {
  	super.onPause();
      whereAmI.disableMyLocation();
  }
}

